package com.qf.day31_boot.controller;

import com.qf.day30_springbootstarter.utils.FileAppender;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.*;

@RestController
@RequestMapping("/export")
public class ExportController {

    @Autowired
    FileAppender fileAppender;

    @Autowired
    ApplicationContext applicationContext;

    @GetMapping("/test1")
    public Map<String, Object> test1() throws IOException {

        final List<String> list = Arrays.asList("luffy", "zoro", "nami", "sanji","franky");

        final String filename = UUID.randomUUID().toString();

        final String finalFilename = filename + ".txt";

        fileAppender.initWriter(finalFilename);

        fileAppender.appendListToFile(list);

        fileAppender.close();

        final HashMap<String, Object> map = new HashMap<>();
        map.put("code", "1");
        map.put("msg", "导出成功");

        return map;

    }

    @GetMapping("/test2")
    public Map<String, Object> test2() throws IOException {

        final FileAppender appender = applicationContext.getBean(FileAppender.class);

        final List<String> list = Arrays.asList("luffy", "zoro", "nami", "sanji","franky");

        final String filename = UUID.randomUUID().toString();

        final String finalFilename = filename + ".txt";

        appender.initWriter(finalFilename);

        appender.appendListToFile(list);

        appender.close();

        final HashMap<String, Object> map = new HashMap<>();
        map.put("code", "1");
        map.put("msg", "导出成功");

        return map;

    }

}
